<template>
  <div>
    <el-button type="danger" @clic="batchDelete"> 批量删除</el-button>
    菜单
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId" :default-expanded-keys="expandedKey" ref="menuTree">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">Append</el-button>

          <el-button type="text" size="mini" @click="edit(data)">edit</el-button>
          <el-button v-if="node.childNodes.length == 0" type="text" size="mini" @click="() => remove(node, data)">Delete</el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" :close-on-click-modal="false">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false"> 取消</el-button>
        <el-button type="primary" @click="submitData">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他组件，（比如： 组件， 工具js, 第三方插件， json 文件等， 图片文件等）
//  例如： import <组件名称>  from '<组件路径>'
export default {
  // import 引入的组件需要注入到对象中才能使用
  name: "category",
  components: {},
  props: {},
  data() {
    // 这里存放数据
    return {
      title: "",
      dialogType: "", // edit ,add
      category: {
        catId: null,
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: "",
        productUnit: ""
      },
      dialogVisible: false,
      expandedKey: [],
      menus: [],
      defaultProps: {
        children: "children",
        label: "name"
      }
    };
  },
  // 计算属性，类似于 data 该奶奶
  computed: {},
  // 监控 data 中的数据变化
  watch: {},
  // 方法合集
  methods: {
    addCategory() {
      // 添加分类
      console.log("添加分类：", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.$message({
          message: "菜单添加成功",
          type: "success"
        });
        // 关闭对话框
        this.dialogVisible = false;
        // 重新加载菜单选项按钮
        this.getMenus();
        // 设置需要 默认展开的菜单
        this.expandedKey = [this.category.parentCid];
      });
    },
    handleClose() { },
    batchDelete() {
      // 批量删除功能
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      let catIds = [];
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i]);
      }

      this.$confirm(`是否批量删除[${catIds}]菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(`/product/category/delete`),
            method: "post",
            data: this.$http.adornData(catIds, false)
          }).then(({ data }) => {
            // 请求成功
            this.$message({
              message: "菜单批量删除成功!",
              type: "success"
            });
            // 刷新菜单
            this.getMenus();
          });
        })
        .catch(() => { });
    },
    append(data) {
      console.log("append", data);
      this.dialogType = "add";
      this.title = "添加分类";

      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.catId = null;
      this.category.sort = 0;
      this.category.showStatus = 1;
    },
    remove(node, data) {
      // 控制台打印
      console.log("remove", node, data);
      // 获取要删除的数据
      let ids = [data.catId];

      this.$confirm(`是否删除【${data.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 确认要删除
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            // 判断是否 执行成功
            if (data && data.code == 0) {
              // 弹框提示用户
              this.$message({
                message: "菜单删除成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  // 重新加载菜单选项按钮
                  this.getMenus();
                  // 设置需要 默认展开的菜单
                  this.expandedKey = [node.parent.data.catId];
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => { });
    },
    edit(data) {
      this.title = "修改分类";
      this.dialogType = "edit";
      this.dialogVisible = true;
      // 发送请求，获取最新节点的数据进行回显
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get"
      }).then(({ data }) => {
        // 请求成功
        this.category.name = data.data.name;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.catId = data.data.catId;
        this.category.parentCid = data.data.parentCid;
      });
    },

    submitData() {
      if (this.dialogType === "add") {
        this.addCategory();
      }
      if (this.dialogType === "edit") {
        this.editCategory();
      }
    },

    editCategory() {
      var { catId, name, icon, productUnit } = this.category;

      var data = {
        catId: catId,
        name: name,
        icon: icon,
        productUnit: productUnit
      };

      // 修改三级分类的数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/update`),
        method: "post",
        data: this.$http.adornData(data, false)
      }).then(({ data }) => {
        // 请求成功
        this.$message({
          message: "菜单修改成功",
          type: "success"
        });
        // 关闭对话框
        this.dialogVisible = false;
        // 重新加载菜单选项按钮
        this.getMenus();
        // 设置需要 默认展开的菜单
        this.expandedKey = [this.category.parentCid];
      });
    },

    getMenus() {
      // 获取三级分类的列表
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get"
      }).then(({ data }) => {
        // console.log('成功获取到菜单数据...', data.data)
        this.menus = data.data;
      });
    }
  },
  // 生命周期 -- 创建完成（可以访问当前this 实例）
  created() {
    this.getMenus();
    // 生命周期 -- 挂载完成 （可以访问 dom元素）
  },
  mounted() { },
  beforeCreate() { }, // 生命周期 -- 创建之前
  beforeMount() { }, // 生命周期 -- 挂载之前
  beforeUpdate() { }, // 生命周期 -- 更新之前
  updated() { }, // 生命周期 -- 更新之后
  beforeDestroy() { }, // 生命周期 -- 销毁之前
  destroyed() { }, // 生命周期 -- 销毁完成
  activated() { } // 如果页面有 keep-alive 缓存功能， 这个函数会触发。
};
</script>

<style scoped></style>
